<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/10/24
 * Time: 9:09 PM
 */

namespace App\Library\Mall;


use App\Events\OrderEvent;
use App\Library\AuthenticatedUser;
use App\Models\Item;
use App\Models\ItemReviews;
use Illuminate\Http\Request;

trait BoughtTrait
{
    use AuthenticatedUser;

    /**
     * 获取订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrder(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->boughts()->find($order_id);

        if ($order) {
            $items = $order->items->map(function ($item){
                $item->thumb = image_url($item->thumb);
                $item->image = image_url($item->image);
                return $item;
            });

            $shop = $order->shop;
            $shop->logo = image_url($shop->logo);
            $shipping = $order->shipping;
            return ajaxReturn(compact('order', 'items', 'shipping', 'shop'));
        } else {
            return ajaxError(404, 'order not found');
        }
    }

    /**
     * 批量获取订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderList(Request $request)
    {
        $offset = $request->input('offset');
        $count  = $request->input('count');
        $offset = $offset ? $offset : 0;
        $count  = $count ? $count : 20;

        $query = $this->user()->boughts()->with('items')->where('buyer_deleted', 0);

        $tradeStatus = $request->input('tradeStatus', 0);
        if ($tradeStatus) {
            $query = $query->where('trade_status', $tradeStatus);
        }

        $tradeCode = $request->input('tradeCode', '');
        if ($tradeCode == 'waitPay')
        {
            $query = $query->where('trade_status', 1);
        }
        if ($tradeCode == 'waitSend')
        {
            $query = $query->where('trade_status', 2);
        }
        if ($tradeCode == 'waitConfirm')
        {
            $query = $query->where('trade_status', 3);
        }
        if ($tradeCode == 'waitRate')
        {
            $query = $query->where('trade_status', 4)->where('buyer_rate', 0);
        }
        if ($tradeCode == 'refunding')
        {
            $query = $query->where('trade_status', 5);
        }

        $items =$query->offset($offset)->limit($count)->orderByDesc('order_id')
            ->get()->map(function ($order){
                $order->quantity = 0;
                $order->items = $order->items->map(function ($item) use (&$order){
                    $item->thumb = image_url($item->thumb);
                    $item->image = image_url($item->image);
                    $order->quantity+= $item->quantity;
                    return $item;
                });
                return $order;
            });

        return ajaxReturn(['items'=>$items]);
    }

    /**
     * 关闭订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function close(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->boughts()->find($order_id);
        if ($order) {
            if (!$order->closed) {
                $closeReason = $request->input('closeReason', '');
                $order->changeToClosed();
                $order->closeReason()->create([
                    'reason'=>$closeReason ? $closeReason : $request->input('otherReason'),
                ]);
            }
        }

        return ajaxReturn();
    }

    /**
     * 提醒卖家发货
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function notice(Request $request)
    {
        return ajaxReturn();
    }

    public function paid(Request $request)
    {
        $order = $this->getOrderWithRequest($request);
        if ($order)
        {
            if ($order->trade_status == 2)
            {
                $order->changeToPaid();
                event(new OrderEvent($order, 'paid'));
            }
        }

        return ajaxReturn();
    }

    /**
     * 确认订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->boughts()->find($order_id);
        if ($order){
            if ($order->trade_status == 3) {
                //货到付款
                $order->changeToReceived();

                $trade = $order->trade;
                if ($trade)
                {
                    //卖增加余额
                    $sellerWallet = $order->seller->wallet()->firstOrCreate([]);
                    $sellerWallet->balance += $trade->total_amount;
                    $sellerWallet->total_income += $trade->total_amount;
                    $sellerWallet->save();
                    //买家扣款
                    $buyerWallet = $order->buyer->wallet()->firstOrCreate([]);
                    $buyerWallet->total_cost+= $trade->total_amount;
                    $buyerWallet->save();
                } else {
                    //买家扣款
                    $buyerWallet = $order->buyer->wallet()->firstOrCreate([]);
                    $buyerWallet->total_cost+= $order->total_fee;
                    $buyerWallet->save();
                }

                event(new OrderEvent($order, 'received'));
            }
        }
        return ajaxReturn();
    }

    /**
     * 申请退款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function refund(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->boughts()->find($order_id);
        if ($order)
        {
            $order->changeToRefunding();
        }

        return ajaxReturn();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->boughts()->find($order_id);
        if ($order)
        {
            $order->update(['buyer_deleted'=>1]);
        }

        return ajaxReturn();
    }

    public function evaluate(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->boughts()->find($order_id);

        if ($order)
        {
            $rate_type = $request->input('rate_type', 1);
            $message   = $request->input('message', '');
            $images    = $request->input('images', []);
            $product_score = $request->input('product_score', 0);
            $wuliu_score   = $request->input('wuliu_score', 0);
            $service_score = $request->input('service_score', 0);

            if (!$order->buyer_rate)
            {
                $shop = $order->shop;
                foreach ($order->items as $item)
                {

                    ItemReviews::insert([
                        'uid'=>$this->user()->uid,
                        'itemid'=>$item->itemid,
                        'order_id'=>$order->order_id,
                        'stars'=>0,
                        'message'=>$message,
                        'images'=>serialize($images),
                        'image_count'=>count($images),
                        'created_at'=>time()
                    ]);
                    Item::where('itemid', $item->itemid)->increment('reviews');

                    if ($shop)
                    {
                        $shop->evaluates()->create([
                            'uid'=>$this->user()->uid,
                            'order_id'=>$order->order_id,
                            'stars'=>0,
                            'message'=>$message,
                            'created_at'=>time(),
                            'product_score'=>$product_score,
                            'wuliu_score'=>$wuliu_score,
                            'service_score'=>$service_score
                        ]);
                    }
                }
                $order->buyer_rate = 1;
                $order->save();
            }
        }

        return ajaxReturn();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Eloquent\Relations\HasMany[]|null
     */
    private function getOrderWithRequest(Request $request)
    {
        $order_id = $request->input('order_id');
        return $this->user()->boughts()->find($order_id);
    }
}
